package com.zzw.springboot.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzw.springboot.common.Constants;
import com.zzw.springboot.common.ErrorResult;
import com.zzw.springboot.common.Result;
import com.zzw.springboot.controller.dto.UserDto;
import com.zzw.springboot.controller.dto.UserPasswordDTO;
import com.zzw.springboot.entity.User;
import com.zzw.springboot.exception.BusinessException;
import com.zzw.springboot.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Objects;

/**
 * @Author zzw2000
 * @Date 2022-05-10 22:11:15
 * @Description User前端控制器
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;

    /**
     * 保存
     *
     * @param user
     * @return
     */
    @PostMapping("/save")
    public Result save(@RequestBody User user) {
        if (user.getId() == null && user.getPassword() == null) {  // 新增用户默认密码
            User one = userService.getOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, user.getUsername()));
            if (Objects.nonNull(one)) {
                throw new BusinessException(ErrorResult.repeatRegister());
            }
            user.setPassword("123456");
        }
        return Result.success(userService.saveOrUpdate(user));
    }

    /**
     * 根据id删除数据
     *
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        return Result.success(userService.removeById(id));
    }

    /**
     * 根据id批量删除user
     *
     * @param ids
     * @return
     */
    @PostMapping("/del/batch")
    public Result delete(@RequestBody List<Integer> ids) {
        return Result.success(userService.removeBatchByIds(ids));
    }

    /**
     * 查询所有
     *
     * @return
     */
    @GetMapping
    public Result findAll() {
        return Result.success(userService.list());
    }

    /**
     * 查询单条记录
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(userService.getById(id));
    }

    /**
     * 分页查询
     *
     * @param pageNum  当前页码
     * @param pageSize 每页显示的条数
     * @return
     */
    @GetMapping("/page")
    public Result findByPage(@RequestParam(defaultValue = "1") int pageNum,
                             @RequestParam(defaultValue = "10") int pageSize,
                             @RequestParam(defaultValue = "") String username,
                             @RequestParam(defaultValue = "") String email,
                             @RequestParam(defaultValue = "") String address) {
        /*IPage<User> page = new Page<>(pageNum, pageSize);
        IPage<User> userPage = userService.page(page, Wrappers.<User>lambdaQuery()
                .like(StringUtils.isNotEmpty(username), User::getUsername, username)
                .like(StringUtils.isNotEmpty(email), User::getEmail, email)
                .like(StringUtils.isNotEmpty(address), User::getAddress, address)
                .orderByDesc(User::getRole)
                .orderByDesc(User::getCreateTime));*/
        return Result.success(userService.findPage(new Page<>(pageNum, pageSize),username,email, address));
    }

    /**
     * 文件导出（Excel）
     *
     * @param response
     * @throws IOException
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws IOException {
        // 从数据库查询出所有的数据
        List<User> list = userService.list();
        // 通过工具类创建writer 写出到磁盘路径
//        ExcelWriter writer = ExcelUtil.getWriter(filesUploadPath + "/用户信息.xlsx");
        // 在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //自定义标题别名
        writer.addHeaderAlias("id", "ID");
        writer.addHeaderAlias("username", "用户名");
        writer.addHeaderAlias("password", "密码");
        writer.addHeaderAlias("nickname", "昵称");
        writer.addHeaderAlias("email", "邮箱");
        writer.addHeaderAlias("phone", "电话");
        writer.addHeaderAlias("address", "地址");
        writer.addHeaderAlias("createTime", "创建时间");
        writer.addHeaderAlias("avatarUrl", "头像");
        writer.addHeaderAlias("role", "角色");

        // 一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(list, true);

        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("用户信息", StandardCharsets.UTF_8);
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();
    }

    /**
     * 文件导入（Excel）
     *
     * @param file
     */
    @PostMapping("/import")
    public Result importFile(MultipartFile file) throws IOException {
        InputStream is = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(is);
        //List<User> list = reader.readAll(User.class);
        //方式1：(推荐) 通过 javabean的方式读取Excel内的对象，但是要求表头必须是英文，跟javabean的属性要对应起来
        //List<User> list = reader.read(0, 1, User.class);
        // 方式2：忽略表头的中文，直接读取表的内容
        List<List<Object>> list = reader.read(1);
        List<User> users = CollUtil.newArrayList();
        for (List<Object> row : list) {
            User user = new User();
            user.setUsername(row.get(0).toString());
            User one = userService.getOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, user.getUsername()));
            if (Objects.nonNull(one)) {
                throw new BusinessException(ErrorResult.repeatRegister(user.getUsername()));
            }
            String password = row.get(1).toString();
            user.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));//row.get(1).toString()
            user.setNickname(row.get(2).toString());
            user.setEmail(row.get(3).toString());
            user.setPhone(row.get(4).toString());
            user.setAddress(row.get(5).toString());
            user.setAvatarUrl(row.get(6).toString());
            users.add(user);
        }
        return Result.success(userService.saveBatch(users));
    }

    /**
     * 用户登录
     *
     * @param userDto 用户请求参数
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody UserDto userDto) {
        String username = userDto.getUsername();
        String password = userDto.getPassword();
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            return Result.error(ErrorResult.paramsError());
        }
        return Result.success(userService.login(userDto));
    }

    /**
     * 用户注册
     *
     * @param userDto
     * @return
     */
    @PostMapping("/register")
    public Result register(@RequestBody UserDto userDto) {
        String username = userDto.getUsername();
        String password = userDto.getPassword();
        String email = userDto.getEmail();
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password) || StringUtils.isBlank(email)) {
            return Result.error(ErrorResult.paramsError());
        }
        return Result.success(userService.register(userDto));
    }

    /**
     * 根据用户名查找用户信息
     *
     * @param username
     * @return
     */
    @GetMapping("/username/{username}")
    public Result getUserByUsername(@PathVariable("username") String username) {
        User user = userService.getOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, username));
        if (Objects.nonNull(user)) {
            return Result.success(user);
        }
        return Result.error(ErrorResult.notFoundUser());
    }

    /**
     * 用户修改密码
     *
     * @param userPasswordDTO
     * @return
     */
    @PostMapping("/password")
    public Result updatePwd(@RequestBody UserPasswordDTO userPasswordDTO) {
        userService.updatePwd(userPasswordDTO);
        return Result.success();
    }

    /**
     * 获取所有老师信息
     * @return
     */
    @GetMapping("/role/ROLE_TEACHER")
    public Result getTeacherByRole() {
        return Result.success(userService.list(Wrappers.<User>lambdaQuery()
                .eq(User::getRole, Constants.ROLE_TEACHER)
                .orderByDesc(User::getCreateTime)));
    }

}

